<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="团队标题" prop="title">
      <el-input v-model="form.title" />
    </el-form-item>
    <el-form-item label="团队描述" prop="description">
      <el-input
        v-model="form.description"
        type="textarea"
        maxlength="200"
        show-word-limit
        :autosize="{ minRows: 4, maxRows: 4}"
      />
    </el-form-item>
    <el-form-item label="图片" prop="image">
      <el-row>
        <el-col :span="12">
          <el-upload
            ref="upload"
            accept=".jpg,.jpeg,.png,.gif"
            :headers="headers"
            name="src"
            :data="form"
            :action="`${host}/user/team/insertOrUpdateTeam`"
            :limit="limitCount"
            :on-success="successImg"
            :on-error="errorImg"
            list-type="picture-card"
            :on-change="uploadChange"
            :before-upload="uploadBefore"
            :class="{hide:hideUpload}"
            :auto-upload="false"
          >
            <i slot="default" class="el-icon-plus" />
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)"><i
                  class="el-icon-zoom-in"
                /></span>
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)"><i
                  class="el-icon-delete"
                /></span>
              </span>
            </div>
          </el-upload>
        </el-col>
        <el-col :span="12">
          <div class="block">
            <el-image style="width: 288px; height: 162px" :src="haveUrl">
              <div slot="error" class="image-slot" />
            </el-image>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-dialog :visible.sync="dialogVisibleImg" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <p style="margin: 0">请选择图片上传：支持JPG、PNG、GIF等格式，图片需不大于5M</p>
      </el-row>
    </el-form-item>
    <el-row>
      <el-col :span="12">
        <el-form-item label="权限" prop="privilege">
          <el-switch v-model="form.privilege" @change="changePrivilege" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item v-if="form.privilege" label="用户邮箱" prop="emails">
      <el-input
        v-model="form.emails"
        type="textarea"
        :autosize="{ minRows: 8, maxRows: 8}"
        placeholder="输入可访问的用户邮箱账号列表，每个用户换行分隔"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('form')">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script>

import { teamByIdAdmin } from '@/api/team'
import { getToken, getUserId } from '@/utils/auth'

export default {
  name: 'AddOrUpdateTeam',
  props: {
    teamId: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      hideUpload: false,
      disabled: false,
      dialogImageUrl: '',
      dialogVisibleImg: false,
      haveUrl: '',
      headers: {
        Authorization: getToken(),
        user_id: getUserId()
      },
      form: {
        teamId: this.teamId,
        userId: getUserId(),
        title: '',
        description: '',
        privilege: false,
        status: false,
        emails: ''
      },
      limitCount: 1,
      rules: {
        title: [{ required: true, message: '请输入团队标题', trigger: 'blur' }],
        description: [{ required: true, message: '请选择团队描述', trigger: 'blur' }],
        emails: [{ required: true, message: '最少输入一个用户邮箱', trigger: 'blur' }]
      },
      host: process.env.VUE_APP_BASE_API
    }
  },
  created() {
    if (this.teamId !== -1) {
      this.teamByIdAdmin()
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.$refs.upload.uploadFiles.length !== 1) {
            this.$message.warning('请选择图片')
            return
          }
          this.$refs.upload.submit()
        }
      })
    },
    successImg(response, file, fileList) {
      this.infoLoad = false
      if (response.code === '00000') {
        this.$message({ message: response.message, type: 'success' })
        this.$emit('updateDialog', false)
      } else {
        this.$message({ message: response.message, type: 'error' })
      }
      this.$refs.upload.uploadFiles = []
      this.imageChange()
    },
    errorImg(response, file, fileList) {
      this.hideUpload = false
      this.imageBtn = true
      this.$message({ message: response.message, type: 'error' })
      this.$refs.upload.uploadFiles = []
      this.imageChange()
    },
    uploadChange(file, fileList) {
      this.imageChange()
    },
    uploadBefore(file) {
      if (file.size > 5242880) {
        this.$message.warning('图片上限为5M')
        this.$refs.upload.uploadFiles = []
        this.imageChange()
        return false
      } else if (file.type !== 'image/jpeg' && file.type !== 'image/gif' && file.type !== 'image/jpg' && file.type !== 'image/png') {
        this.$refs.upload.uploadFiles = []
        this.$message.warning('文件类型限制为jpg,jpeg,gif,png')
        this.imageChange()
        return false
      } else {
        this.infoLoad = true
        return true
      }
    },
    imageChange() {
      this.hideUpload = this.$refs.upload.uploadFiles.length >= this.limitCount
      this.imageBtn = this.$refs.upload.uploadFiles.length < this.limitCount
    },
    handleRemove(file) {
      this.$refs.upload.uploadFiles = []
      this.imageChange()
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisibleImg = true
    },
    changePrivilege() {
      this.form.emails = ''
    },
    teamByIdAdmin() {
      teamByIdAdmin({ teamId: this.teamId }).then(res => {
        this.form.title = res.data.title
        this.form.description = res.data.description
        this.form.status = res.data.status === 1
        this.form.privilege = res.data.privilege === 1
        this.form.emails = res.data.emails || ''
        this.haveUrl = res.data.src
      })
    }
  }
}
</script>

<style scoped>
::v-deep .hide .el-upload--picture-card {
  display: none;
}
</style>
